import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

let cart=window.JSON.parse(localStorage.getItem('cart')||'[]')
const store=new Vuex.Store({
	state:{
		count:11,
		cart:cart
	},
	mutations:{
		addToCart(state,goods){
			let flag=false
			var isExit=state.cart.some(v=>{
				if(v.id==goods.id){
					v.count+=goods.count
					flag=true
					return true
				}
			})
			if(!isExit){
              state.cart.push(goods)
			}
			localStorage.setItem('cart',window.JSON.stringify(state.cart))
		},
		updateShopcartCount(state,goods){
			state.cart.some(v=>{
				if(v.id==goods.id){
					v.count=goods.count
					return true
				}
			})
			localStorage.setItem('cart',window.JSON.stringify(state.cart))
		},
		delShopcartCount(state,id){
			var index=state.cart.findIndex(v=>v.id==id)
			state.cart.splice(index,1)
			localStorage.setItem('cart',window.JSON.stringify(state.cart))
		},
		changeShopcartSelected(state,id){
			state.cart.some(v=>{
				if(v.id==id){
					v.selected=!v.selected
					if(!v.selected){

					}
					return true
				}
			})
			localStorage.setItem('cart',window.JSON.stringify(state.cart))
		}
		
	},
	getters:{
		totalCount(state){
			let total=0;
			state.cart.forEach(item=>{
				total+=item.count
			})
			return total
		},
		idStr(state){
         let arr=[]
         state.cart.forEach(item=>{
         	arr.push(item.id)
         })
         return arr.join(",")
		},
		countObj(state){
			let o={}
			state.cart.forEach(item=>o[item.id]=item.count)
			return o
		},
		selectedObj(state){
			let o={}
			state.cart.forEach(item=>o[item.id]=item.selected)
			return o
		},
		selectedCount(state){
			let c=0;
			state.cart.forEach(item=>{
				if(item.selected){
					c+=item.count
				}
				
			})
			return c
		},
		amount(state){
			let c=0;
			state.cart.forEach(item=>{
				if(item.selected){
					c+=item.count*item.price
				}
				
			})
			return c

		},
	}
})
export default store